import { message } from '@/utils/message'
import type { PaginationProps } from '@pureadmin/table'
import { ModalShowType } from '@/types/common'
import { computed, onMounted, reactive, ref, toRaw } from 'vue'
import { columnWidthConfig } from '@/config/table'
import { omitEmptyValue } from '@/utils/common'
import { useRouter } from 'vue-router'
import { getMcpList, removeMcp } from '@/api/mcp-mall/mcp-mall'
import { ElMessageBox } from 'element-plus'

export function useData() {
  const router = useRouter()
  const form = reactive({
    ids: [],
    keywords: '',
    searchValue: '',
    createByName: '',
    startDate: null,
    endDate: null,
    // status: ""
  })
  const dataList = ref([])
  const loading = ref(true)
  const mcpId = ref<string>()
  const modalShow = ref(ModalShowType.Hide)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  })

  const showSelection = false // 控制是否展示选择列
  const columns: TableColumnList = [
    {
      type: 'selection',
      width: columnWidthConfig.checkbox,
      align: 'left',
    },
    { label: 'mcpId', prop: 'mcpId' },
    { label: 'MCP名称', prop: 'mcpName' },
    { label: 'MCP别名', prop: 'alias' },
    { label: '类型', prop: 'type' },
    { label: '提供方', prop: 'provider' },
    {
      label: 'MCP LOGO图标',
      prop: 'mcpImgUrl',
      cellRenderer: ({ row, ..._props }) => (
        <div class="flex justify-center items-center">
          <img src={row.mcpImgUrl} alt="MCP Logo" width="50" height="50" />
        </div>
      ),
    },
    { label: '标签', prop: 'tags' },
    { label: '描述', prop: 'description' },
    {
      label: '状态',
      prop: 'status',
      cellRenderer: ({ row, ..._props }) => {
        return row.status === '0' ? '启用' : '禁用'
      },
    },
    {
      label: '操作',
      prop: 'type',
      fixed: 'right',
      minWidth: 100,
      cellRenderer: ({ row, ..._props }) => (
        <div class="flex align-middle justify-around">
          <div
            class="text-blue-400 cursor-pointer"
            onClick={() => {
              router.push({
                path: '/mcp-mall/detail',
                query: { mcpId: row.mcpId },
              })
            }}
          >
            MCP详情
          </div>
          <div
            class="text-blue-400 cursor-pointer"
            onClick={() => {
              modalShow.value = ModalShowType.Edit
              mcpId.value = row.mcpId
            }}
          >
            编辑
          </div>
          <div
            class="text-red-400 cursor-pointer"
            onClick={() => {
              handleDelete(row.mcpId)
            }}
          >
            删除
          </div>
        </div>
      ),
    },
  ]

  const buttonClass = computed(() => {
    return [
      '!h-[20px]',
      'reset-margin',
      '!text-gray-500',
      'dark:!text-white',
      'dark:hover:!text-primary',
    ]
  })

  function handleUpdate(row) {
    console.log(row)
  }

  async function handleDelete(id) {
    ElMessageBox.confirm('数据一经删除不可恢复，请再次确认！', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await removeMcp(id)
      message('删除成功', { type: 'success' })
      await onSearch()
    })
  }

  async function handleSizeChange(val: number) {
    console.log(`${val} items per page`)
    await onSearch(pagination.currentPage, val)
  }

  async function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`)
    await onSearch(val, pagination.pageSize)
  }

  const selectedRows = ref([])

  function handleSelectionChange(val) {
    selectedRows.value = val
    form.ids = val.map((item) => item.costId)
  }

  async function onSearch(pageNum = 1, pageSize = 10) {
    loading.value = true
    const data = await getMcpList({
      ...omitEmptyValue(toRaw(form)),
      pageNum,
      pageSize,
    })

    dataList.value = data.rows
    pagination.currentPage = pageNum
    pagination.pageSize = pageSize
    pagination.total = data.total
    setTimeout(() => {
      loading.value = false
    }, 500)
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    onSearch()
  }

  const statusDict = ref<Map<number, string>>(new Map())

  onMounted(onSearch)

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    showSelection,
    buttonClass,
    statusDict,
    modalShow,
    mcpId,
    selectedRows,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
  }
}
